﻿using System;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections.Generic;
using SystemX.Web;

namespace SystemX.WebControls
{
	public class GoogleJSLoader:WebControl
	{
		const string STR_APIRoot = "<script type=\"text/javascript\" src=\"http://www.google.com/jsapi{0}\"></script>\n";
		/// <summary>
		/// If you don't yet have a Google API key, you can sign up for an API key for free
		/// </summary>
		public string APIKey { get; set; }
		/// <summary>
		/// [{n:'jquery',v:'1.3.2'},{n:'xx',v:'yy'}]
		/// </summary>
		public string ModulesToLoad { get; set; }

		private static readonly object _SynHelper = new object();
		private static string _Html;
		public  string OuterHtml
		{
			get
			{
				if (_Html == null)
				{
					lock (_SynHelper)
					{
						if (_Html == null)
						{
							_Html = LoadAll();
						}
					}
				}
				return _Html;
			}
		}

		protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			writer.Write(OuterHtml);
		}

		#region helper staff
		private string LoadAll()
		{
			if (string.IsNullOrEmpty(ModulesToLoad)) return "";

			var sb = new StringBuilder();
			sb.AppendFormat(STR_APIRoot, string.IsNullOrEmpty(APIKey) ? "" : String.Format("?key={0}", APIKey));

			try
			{
				var modules = ModulesToLoad.DeserializeJSONStr<List<JsModule>>();
				sb.AppendLine("<script type=\"text/javascript\">\n//<![CDATA[");
				modules.ForEach(x => {
					if (!string.IsNullOrEmpty(x.o)) {
						sb.AppendFormat("google.load(\"{0}\",\"{1}\",\"{2}\");", x.n, x.v, x.o);
					} else {
						sb.AppendFormat("google.load(\"{0}\",\"{1}\");", x.n, x.v);
					}

				});
				sb.AppendLine("\n//]]>\n</script>");
			}
			catch (Exception ex) {
				return "";
			}

			return sb.ToString();
		}


		private class JsModule {
			/// <summary>
			/// 'name
			/// </summary>
			public string n { get; set; }
			/// <summary>
			/// version
			/// </summary>
			public string v { get; set; }
			/// <summary>
			/// option settings
			/// </summary>
			public string o { get; set; }
		}
		#endregion
	}
}
